from django.http import JsonResponse
from rest_framework import serializers, viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from ext.view import JKAPIView
from ext.per import UserPermission,ManagerPermission,BossPermission
from ext.throttle import MyThrottle
from rest_framework.versioning import QueryParameterVersioning
from api import models
import datetime
class InfoUser(APIView):
    # authentication_classes = []
    def get(self,request):
        print(request.data)
        print("33333",request.user,request.auth)
        return JsonResponse({"status":True, "message":"Hello World"})

    def post(self,request):
        print("------------")
        print(request._request.body)
        return Response("我很牛逼")

class Order(JKAPIView):
    permission_classes = [BossPermission,ManagerPermission,]
    def get(self,request):
        return Response("OrderInfo")

class  Avator(JKAPIView):
    permission_classes = [UserPermission,]
    throttle_classes = [MyThrottle,]
    def get(self,request):
        return Response("Avator")

class Home(APIView):
    authentication_classes = []
    versioning_class = QueryParameterVersioning
    def get(self,request):
        return Response("hahahahah")

    def post(self,request,*args,**kwargs):
        from rest_framework.parsers import JSONParser,FormParser,FileUploadParser
        from rest_framework.negotiation import DefaultContentNegotiation
        #所有解析器
        parser_classes = [JSONParser,FormParser]
        #根据请求匹配对应的解析器
        content_negotiation_class = DefaultContentNegotiation
        print(request.data)
        return Response("aaaa")



class DepartmentSerializer(serializers.Serializer):
    title = serializers.CharField()
    count = serializers.IntegerField()

# class DepartmentSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = models.Depart
#         fields = '__all__'

class Department(APIView):
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        #1.从数据库中获取数据
        depart_obj = models.Depart.objects.all().first()
        #depart_obj = models.Depart.objects.all()
        #2.转换成JSON格式
        ser = DepartmentSerializer(instance=depart_obj)
        #ser = DepartmentSerializer(instance=depart_obj,many=True) 可以序列化多个对象
        print(ser.data)
        #3.返回给用户
        context = {"data":ser.data}
        return Response(context)

class D1(serializers.ModelSerializer):
    class Meta:
        model = models.Depart
        fields = "__all__"

class D2(serializers.ModelSerializer):
    class Meta:
        model = models.Tag
        fields = "__all__"

class UserSerializer(serializers.ModelSerializer):
    # xx = serializers.CharField(source="get_gender_display")  自定制字段
    # ctime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")

    # xxx = serializers.SerializerMethodField()   自定义序列化
    # def get_xxx(self,obj):
    #     return "aaaaa"
    # xxx = serializers.SerializerMethodField()
    depart = D1()
    tags = D2(many=True)
    class Meta:
        model = models.UserInfo2
        fields = ["name","gender","depart","tags"]
    # def get_xxx(self,obj):
    #     queryset = obj.tags.all()
    #     result = [{"id":tag.id,"caption":tag.caption} for tag in queryset]
    #     print(queryset)
    #     return result
class UserView(APIView):
    authentication_classes = []
    def get(self,request,*args,**kwargs):
        models.UserInfo2.objects.all().update(ctime=datetime.datetime.now())
        queryset = models.UserInfo2.objects.all()
        ser = UserSerializer(instance=queryset,many=True)
        context = {"status":True, "data":ser.data}
        return Response(context)
class LoveSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)

class LoveModelSerializer(viewsets.ModelViewSet):
    class Meta:
        model = models.Depart
        fields = ["title","order"]
        extra_kwargs = {
            "title": {"max_length": 50,"min_length":1},
            "order": {"min_value":1}
        }
class LoveView(APIView):
    authentication_classes = []
    def post(self,request,*args,**kwargs):
        #1.获取原始数据
        print(request.data)
        #2.校验
        ser = LoveSerializer(data=request.data)
        # ser.is_valid(raise_exception=True)   校验成功继续下面代码，校验失败抛出错误异常
        if ser.is_valid():
            print(ser.validated_data)
        else:
            print(ser.errors)
        return Response("i love you")

class UsModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Depart
        fields = ["title","order"]
        extra_kwargs = {
            "title": {"max_length": 50,"min_length":1},
            "order": {"min_value":1}
        }

class UsView(APIView):
    authentication_classes = []
    def post(self,request,*args,**kwargs):
        ser = UsModelSerializer(data=request.data)
        if ser.is_valid():
            print("视图",ser.validated_data)
            ser.asve()
        else:
            print("视图",ser.errors)
        return Response("HAHAHAHAHAHAHAH")

class DpSerializer(serializers.ModelSerializer):
    #v1 = serializers.CharField(read_only=True,write_only=True)#read_only序列化的时候用，write_only校验的时候用
    class Meta:
        model = models.Depart
        fields = ["id","title","order","count"]
    extra_kwargs = {
        "id":{"read_only":True},
        "count":{"write_only":True}
    }
class DpView(APIView):
    authentication_classes = []

    def post(self,request,*args,**kwargs):
        ser = DpSerializer(data=request.data)
        if ser.is_valid():
            instance = ser.save()
            print(instance)
        else:
            print(ser.errors)
        return Response("nb")

class Tb2Serializer(serializers.ModelSerializer):
    gender = serializers.CharField(read_only=True, source="get_gender_display")
    class Meta:
        model = models.UserInfo2
        fields = ["name","age","gender","depart","tags"]
class TbSerializer(serializers.ModelSerializer):
    gender = serializers.SerializerMethodField()

    class Meta:
        model = models.UserInfo2
        fields = ["name","age","gender","depart","tags"]

class TbView(APIView):
    authentication_classes = []
    def post(self,request,*args,**kwargs):
        ser = TbSerializer(data=request.data)
        if ser.is_valid():
            # ser.validated_data.pop("gen")
            instance = ser.save()
            return Response(ser.data)
        else:
            return Response(ser.errors)

from django import forms

# class d(forms.ModelForm):
#     form.is_valid`
from ext.hook import JKSerializer
class JkViewSerializer(JKSerializer, serializers.ModelSerializer):
    # n= serializers.IntegerField()
    class Meta:
        model = models.UserInfo2
        fields = ["name","age","gender","depart"]
    def jk_gender(self,obj):
        return obj.get_gender_display()



class JkView(APIView):
    authentication_classes = []
    def post(self,request,*args,**kwargs):
        ser = JkViewSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        else:
            return Response(ser.errors)




